#include "base\macros.h";
WAITINIT(vehrespawn);

if (isServer) then {
	private ["_unit","_respawn_timer","_unit_type","_init_pos","_init_dir","_time_empty"];
	_unit = _this;
	_respawn_timer = 450;
	_time_empty = 0;
	if (typename _this == typename []) then {
		_unit = _this select 0;
		if (count _this > 1) then { _respawn_timer = _this select 1; };
	};
	_init_pos = getPos _unit;
	_init_dir = getDir _unit;
	_unit_type = typeof _unit;
	while {true} do {
		if (!alive _unit) then {
			sleep 10;
			diag_log format["Respawning Destroyed Unit: %1",_unit_type];
			if (!isnull _unit) then { deleteVehicle _unit; };
			_unit = _unit_type createVehicle _init_pos;
			_unit setDir _init_dir;
		} else {
			if ((_unit distance _init_pos) > 100) then {
				if (_time_empty > 0) then {
					if (count (crew _unit) > 0) then {
						_time_empty = 0;
					} else {
						if ((time - _time_empty) > _respawn_timer) then {
							diag_log format["Respawning Empty Unit: %1 (%2)",_unit_type, time];
							if (damage _unit > 0.4) then {
								_unit setPos [0,0,0];
								_unit setDamage 1;
							} else {
								_unit setPos _init_pos;
								_unit setDir _init_dir;
							};
						};
					};
				} else {
					if (count (crew _unit) <= 0) then {
						diag_log format["Detected Empty Unit: %1 (%2)",_unit_type, time];
						_time_empty = time;
					} else {
						_time_empty = 0;
					};
				};
			};
		};
		sleep (15 + random (15));
	};
};